<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\exception\HttpException;
use app\common\model;
use think\Loader;
use think\Config;
use think\Db;

class Batch extends Controller
{
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("batch")) {
            $map['batch'] = ["like", "%" . $this->request->param("batch") . "%"];
        }
        if ($this->request->param("company_type")) {
            $company_type = $this->request->param("company_type");
            if($company_type == '折扣'){
                $map['company_type'] = ["like", "%" . 1 . "%"];
            }elseif($company_type == '金额'){
                $map['company_type'] = ["like", "%" . 2 . "%"];
            }
        }
        if ($this->request->param("company_value")) {
            $map['company_value'] = ["like", "%" . $this->request->param("company_value") . "%"];
        }
        if ($this->request->param("offline_type")) {
            $offline_type = $this->request->param("offline_type");
            if($offline_type == '折扣'){
                $map['offline_type'] = ["like", "%" . 1 . "%"];
            }elseif($offline_type == '金额'){
                $map['offline_type'] = ["like", "%" . 2 . "%"];
            }
        }
        if ($this->request->param("offline_value")) {
            $map['offline_value'] = ["like", "%" . $this->request->param("offline_value") . "%"];
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $model = $this->getModel();

        // 列表过滤器，生成查询Map对象
        $map = $this->search($model, [$this->fieldIsDelete => $this::$isdelete]);

        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }

        $this->datalist($model, $map);

        return $this->view->fetch();
    }

    /**
     * 回收站
     * @return mixed
     */
    public function recycleBin()
    {
        $this::$isdelete = 1;

        return $this->index();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 插入
            $form = $this->request->except(['id']);

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($form)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
            //数据重构
            $num  = $form['num'];
            $card['batch']   = $form['batch'];
            $batch['batch']  = $form['batch'];
            $expiry          = $form['expiry'];
            $batch['expiry'] = strtotime($expiry.' month',time());
            $batch['company_type']  = $form['company_type'];
            $batch['company_value'] = $form['company_value'];
            $batch['offline_type']  = $form['offline_type'];
            $batch['offline_value'] = $form['offline_value'];

            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                //在批次表中插入表单信息
                $model = new $modelClass();
                $ret = $model->isUpdate(false)->save($batch);

                //在优惠卡表中循环插入对应数目信息   助手函数简单插入
                for($i = 0; $i < $num; $i++){
                    $number = Db::name('card')->max('number')+1;
                    $card['number'] = ($number > 123456) ? $number : 123456;
                    $model = new model\Card();
                    $ret = $model->isUpdate(false)->save($card);
                }
            }

            return ajax_return_adv('添加成功');
        } else {
            // 添加
            $number = Db::name('card')->max('number')+1;
            $number = ($number > 123456)? $number : 123456;
            $batch = date('YmdHi',time());
            return $this->view->fetch('add',['number'=>$number,'batch'=>$batch]);
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
            //数据重构
            $data['num'] = 1;
            unset($data['start_num']);
            unset($data['end_num']);
            $expiry = $data['expiry'];
            $create_time = Db::name('batch')->field('create_time')->where(['id'=>$data['id']])->find()['create_time'];
            $expiry = strtotime($expiry.' month',$create_time);
            $data['expiry'] = $expiry;

            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                // 使用模型更新，可以在模型中定义更高级的操作
                unset($data['num']);
                $model = new $modelClass();
                $ret = $model->isUpdate(true)->save($data, ['id' => $data['id']]);
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }
            //根据批次号id 查询优惠卡表该批次号码段
            $batch = Db::name('batch')->field('batch')->where('id',$id)->find();
            $batch = $batch['batch'];
            $start_num = Db::name('card')->where(['batch'=>$batch])->min('number');
            $end_num   = Db::name('card')->where(['batch'=>$batch])->max('number');
            $expiry      = Db::name('batch')->field('expiry')->where('id',$id)->find()['expiry'];
            $create_time = Db::name('batch')->field('create_time')->where('id',$id)->find()['create_time'];
            $expiry = round( ($expiry-$create_time)/(60*60*24*30));

            $this->view->assign("vo", $vo);
            $this->view->assign("batch", $vo['batch']);
            $this->view->assign('start_num',$start_num);
            $this->view->assign('end_num',$end_num);
            $this->view->assign('expiry',$expiry);

            return $this->view->fetch();
        }
    }

    /**
     * 默认删除操作
     */
    public function delete()
    {
        return $this->updateField($this->fieldIsDelete, 1, "移动到回收站成功");
    }

    /**
     * 从回收站恢复
     */
    public function recycle()
    {
        return $this->updateField($this->fieldIsDelete, 0, "恢复成功");
    }

    /**
     * 永久删除
     */
    public function deleteForever()
    {
        Db::startTrans();
        try {
            $model = $this->getModel();
            $pk = $model->getPk();
            $ids = $this->request->param($pk);
            $where[$pk] = ["in", $ids];
            /*
             * 个人修改
             */
            //根据删除批次信息id  查询对应批次号
            $batchs = Db::name('batch')->field('batch')->where($where)->select();
            foreach($batchs as $k=>$v){
                $batch[] = $v['batch'];
            }
            $a['batch'] = ['in',$batch];
            //根据批次号 在优惠卡表中查询该批次号下的所有优惠卡  执行删除
            $res = Db::name('card')->where($a)->delete();
            //根据批次id 删除对应批次信息
            $result = $model->where($where)->delete();

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            return ajax_return_adv_error($e->getMessage());
        }

        return ajax_return_adv("删除成功");

    }

    /**
     * 清空回收站
     */
    public function clear()
    {
        Db::startTrans();
        try{
            $model = $this->getModel();
            $where[$this->fieldIsDelete] = 1;
            //查询批次表中 isdelete字段为1的所有批次（batch）
            $batchs = Db::name('batch')->field('batch')->where(['isdelete'=>1])->select();
            foreach($batchs as $k=>$v){
                $batch[] = $v['batch'];
            }
            $a['batch'] = ['in',$batch];
            //根据批次信息  在优惠卡表中查出所有对应批次的优惠卡  执行删除
            $res = Db::name('card')->where($a)->delete();
            //删除批次表中对应信息
            $result = $model->where($where)->delete();

            //提交事务
            Db::commit();
        }catch (\Exception $e){
            //回滚事务
            Db::rollback();
            return ajax_return_adv_error($e->getMessage());
        }

        return ajax_return_adv("清空回收站成功");
    }

    /**
     * 保存排序
     */
    public function saveOrder()
    {
        $param = $this->request->param();
        if (!isset($param['sort'])) {
            return ajax_return_adv_error('缺少参数');
        }

        $model = $this->getModel();
        foreach ($param['sort'] as $id => $sort) {
            $model->where('id', $id)->update(['sort' => $sort]);
        }

        return ajax_return_adv('保存排序成功', '');
    }
    
}
